import math
import os
from datetime import datetime, timedelta

import pandas as pd


def read_excel(file_path):
    # 使用 read_excel 函数读取数据
    df = pd.read_excel(file_path)
    # 打印每一行的数据
    result = {}
    for index, row in df.iterrows():
        data = row.to_dict()
        # target_data = {"updateTime":data['updateTime'],"secLevel":data['secLevel'],"orgCode":data['orgCode']}
        target_data = datetime.strptime(data['updateTime'], "%Y-%m-%d %H:%M:%S")
        day = data['updateTime'].split(" ")[0]
        upOrgCode = data['upOrgCode']
        if day not in result.keys():
            result[day] = {}
            result[day][upOrgCode] = [target_data]
        else:
            if upOrgCode not in result[day].keys():
                result[day][upOrgCode] = [target_data]
            else:
                result[day][upOrgCode].append(target_data)

    return result


def read_csv_to_dict(file_path):
    df = pd.read_csv(file_path)
    data = df.to_dict(orient='records')
    return data


def loss_speed(data):
    last_speed = None
    for item in data:
        # print(item)
        if pd.isna(item['mean_speed']):
            # print(item)
            if last_speed is not None:
                item['mean_speed'] = last_speed
            else:
                item['mean_speed'] = 70
        else:
            item['mean_speed'] = round(item['mean_speed']*3.6, 2)
        last_speed = item['mean_speed']
    return data


def add_time_to_intervals(time_list, timee, duration_minutes):
    if not time_list:
        # 如果 time_list 为空，添加一个新的时间区间
        time_list.append([timee])
    else:
        # 遍历现有的时间区间
        for interval in time_list:
            last_time = interval[-1]  # 获取时间区间的最后一个时间点
            if timee - last_time < timedelta(minutes=duration_minutes):
                # 如果 timee 与最后一个时间点相差小于6分钟，添加到当前区间
                interval.append(timee)
                return  # 添加后退出函数
        # 如果没有找到符合条件的时间区间，添加一个新的时间区间
        time_list.append([timee])


def find_overlap_and_non_overlap(start_A, end_A, start_B, end_B):
    # 计算重合区间
    overlap_start = max(start_A, start_B)
    overlap_end = min(end_A, end_B)
    if overlap_start < overlap_end:
        overlap = (overlap_start, overlap_end)
    else:
        overlap = None
        non_overlap_A = [(start_A, end_A)]
        non_overlap_B = [(start_B, end_B)]
        return overlap, non_overlap_A, non_overlap_B

    # 计算A的非重合区间
    non_overlap_A = []
    if start_A < overlap_start:
        non_overlap_A.append((start_A, overlap_start))
    if overlap_end < end_A:
        non_overlap_A.append((overlap_end + timedelta(minutes=1), end_A))
    # 计算B的非重合区间
    non_overlap_B = []
    if start_B < overlap_start:
        non_overlap_B.append((start_B, overlap_start))
    if overlap_end < end_B:
        non_overlap_B.append((overlap_end + timedelta(minutes=1), end_B))

    return overlap, non_overlap_A, non_overlap_B


def jida_deal(jida_result):
    jida_time_dict = {}
    for day, up_orgCode_info in jida_result.items():
        jida_time_dict[day] = {}
        for up_orgCode, time_list in up_orgCode_info.items():
            jida_time_dict[day][up_orgCode] = {"time_list": [], "duration": 0}
            for timee in time_list:
                add_time_to_intervals(jida_time_dict[day][up_orgCode]["time_list"], timee, 6)
            for interval in jida_time_dict[day][up_orgCode]["time_list"]:
                start_time = interval[0]
                end_time = interval[-1]
                if len(interval) == 1:
                    end_time = end_time + timedelta(minutes=1)
                duration = (end_time - start_time).total_seconds()
                # print(f"时间区间: {start_time} - {end_time}, 时长: {duration}s")
                jida_time_dict[day][up_orgCode]["duration"] += duration
    return jida_time_dict


def A(start_time, end_time):
    # 初始化一个空列表来存储小区间
    intervals = []
    # 使用当前时间作为起始点，每次增加1分钟，直到达到结束时间
    current_time = start_time
    while current_time < end_time:
        # 计算下一个时间点（不包含结束时间的那一分钟的后一秒，但因为我们是在<的条件下循环，所以没关系）
        next_time = current_time + timedelta(minutes=1)
        intervals.append([current_time, min(next_time, end_time)])
        # 更新当前时间点为下一个时间点（准备下一次循环）
        current_time = next_time

    return intervals


def run(data_list, jida_time_data):
    # print(jida_time_data)
    speed_time_list = []
    speed_duration = 0
    positive_duration = 0
    incorrect_duration = 0
    missed_duration = 0
    new_speed_time_list = []
    temp_dict = {}

    for data in data_list:
        if data['mean_speed'] <= 40:
            timee = datetime.strptime(data['transtime_up'], '%Y-%m-%d %H:%M:%S')
            add_time_to_intervals(speed_time_list, timee, 6)

    for time_list in speed_time_list:
        interval = time_list.copy()
        start_time = interval[0]
        end_time = interval[-1]
        if len(interval) == 1:
            end_time = end_time + timedelta(minutes=5)
        a = A(start_time, end_time)
        new_speed_time_list += a
    # print(new_speed_time_list)
    if not jida_time_data:
        if len(speed_time_list) == 0:
            return 100, 0, 0
        else:
            return 0, 0, 100
    if jida_time_data and len(speed_time_list) == 0:
        return 0, 100, 0
    # print(new_speed_time_list)
    for m in range(len(speed_time_list)):
        interval = speed_time_list[m]
        start_time = interval[0]
        end_time = interval[-1]
        if len(interval) == 1:
            end_time = end_time + timedelta(minutes=5)
        duration = (end_time - start_time).total_seconds()
        # print(f"时间区间: {start_time} - {end_time}, 时长: {duration}s")
        speed_duration += duration

        # 时间对比
        for n in range(len(jida_time_data['time_list'])):
            jida_data = jida_time_data['time_list'][n]
            start_time_jida = jida_data[0]
            end_time_jida = jida_data[-1]
            if len(jida_data) == 1:
                end_time_jida = end_time_jida + timedelta(minutes=1)
            overlap, non_overlap_speed, non_overlap_jida = find_overlap_and_non_overlap(start_time, end_time,
                                                                                        start_time_jida, end_time_jida)

            if overlap is not None:
                positive_duration += (overlap[1] - overlap[0]).total_seconds()
            # for i in range(len(non_overlap_speed)):
            #     missed_duration += (non_overlap_speed[i][1] - non_overlap_speed[i][0]).total_seconds()
            # for j in range(len(non_overlap_jida)):
            #     incorrect_duration += (non_overlap_jida[j][1] - non_overlap_jida[j][0]).total_seconds()
            # if overlap is None:
            #     for i in range(len(non_overlap_speed)):
            #         missed_duration += (non_overlap_speed[i][1] - non_overlap_speed[i][0]).total_seconds()
            #     for j in range(len(non_overlap_jida)):
            #         incorrect_duration += (non_overlap_jida[j][1] - non_overlap_jida[j][0]).total_seconds()

    incorrect_duration = jida_time_data['duration'] - positive_duration
    missed_duration = speed_duration - positive_duration

    print(positive_duration, incorrect_duration, missed_duration, speed_duration, jida_time_data['duration'])
    # 正检
    positive = round(positive_duration / speed_duration * 100, 2)
    # 错检
    incorrect = round(incorrect_duration / jida_time_data['duration'] * 100, 2)
    # 漏检
    missed = round(missed_duration / speed_duration * 100, 2)

    return positive, incorrect, missed


def main(jida_file_path, dir_path, save_path, save_path1):
    jida_result = read_excel(jida_file_path)
    jida_time_dict = jida_deal(jida_result)

    data_dict = {}

    with open(save_path, 'w', encoding='utf-8') as f:
        f.write(f"日期,区间,正检率,错检率,漏检率\n")

    for subdir in get_direct_subdirectories(dir_path):
        print(subdir)
        day_str = os.path.basename(subdir).split('-')[1]
        # 使用字符串切片来提取年、月、日
        year = day_str[:4]
        month = day_str[4:6]
        day = day_str[6:]
        # 使用格式化字符串来组合成新的日期格式
        day_date = f"{year}-{month}-{day}"
        orgCode_data = os.path.basename(subdir).split('-')[0]
        up_orgCode_data = orgCode_data.split(',')[0]
        orgCode_str = up_orgCode_data + orgCode_data.split(',')[1]
        file_path = os.path.join(subdir, 'car_time_data.csv')
        data = read_csv_to_dict(file_path)
        new_data = loss_speed(data)
        if up_orgCode_data not in jida_time_dict[day_date]:
            positive, incorrect, missed = run(new_data, [])
        else:
            positive, incorrect, missed = run(new_data, jida_time_dict[day_date][up_orgCode_data])
        if day_date not in data_dict.keys():
            data_dict[day_date] = {}
        data_dict[day_date][orgCode_str] = {"positive": positive, "incorrect": incorrect, "missed": missed}
        with open(save_path, 'a', encoding='utf-8') as f:
            f.write(f"{day_date},{orgCode_str},{positive},{incorrect},{missed}\n")

    with open(save_path1, 'w', encoding='utf-8') as f:
        for day, day_date in data_dict.items():
            orgCode_list = list(day_date.keys())
            result = ",".join(str(orgCode) for orgCode in orgCode_list)
            f.write(f"{day},{result}\n")
            positive_result = ",".join(str(day_date[orgCode]["positive"]) for orgCode in orgCode_list)
            f.write(f"正检率,{positive_result}\n")
            incorrect_result = ",".join(str(day_date[orgCode]["incorrect"]) for orgCode in orgCode_list)
            f.write(f"错检率,{incorrect_result}\n")
            missed_result = ",".join(str(day_date[orgCode]["missed"]) for orgCode in orgCode_list)
            f.write(f"漏检率,{missed_result}\n")

            f.write(f"\n")


def get_direct_subdirectories(directory):
    """
    获取目录下的直接子文件夹（不递归）。

    :param directory: 要检查的目录路径。
    """
    try:
        for entry in os.scandir(directory):
            if entry.is_dir():
                yield entry.path
    except FileNotFoundError:
        print(f"目录 {directory} 不存在")
    except PermissionError:
        print(f"没有权限访问目录 {directory}")


if __name__ == '__main__':
    jida_file_path = r"D:\下载\飞书文件下载\jida_event.xlsx"
    dir_path = r'D:\GJ\项目\铜锣山\data\data_output'
    save_path = r"D:\GJ\项目\铜锣山\data\jida_event.csv"
    save_path1 = r"D:\GJ\项目\铜锣山\data\jida_event_1.csv"
    main(jida_file_path, dir_path, save_path, save_path1)



